<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
//  Copyright (C) 2004-2006  Autodesk, Inc.
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of version 2.1 of the GNU Lesser
//  General Public License as published by the Free Software Foundation.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-->
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta http-equiv="content-script-type" content="text/javascript">
    <meta http-equiv="content-style-type" content="text/css">
	<link href="<?php echo ESTILO?>/viewer.css" rel="stylesheet" type="text/css">
</head>

<body onLoad="OnPageLoad()"> 

<?php include ("config.php");
	  include ("utils.php");
	  include(ROOT_DIR_CLASES.'/cCliente.php');
	  include(ROOT_DIR_CLASES.'/point.php');
	  include(ROOT_DIR_CLASES.'/log.php');
?>	
<?php
    //ini_set("display_errors","1");
    //error_reporting(E_ALL);
require_once('../common.php');
require_once($webExtensionsDirectory . 'www/mapviewerphp/layerdefinitionfactory.php');	
require_once('layer_functions.php');
try
{
	//---------------------------------------------------//
		$cuenta=$_SESSION['cuentaSelect'];
		$filtroHistorico = $_SESSION['filtroHistorico'] + 1;
		$_SESSION['filtroHistorico'] = $filtroHistorico;
		$thickness = $_REQUEST['thickness'];
		$mostrarSentido = $_SESSION['mostrarSentido'];
		$distanciaRecorrida = $_SESSION['distanciaRecorrida'];
		//--------------------------------------        
		$datosIdentificacion = BykomCliente::Consulta_Datos_Identificacion_Avl($cuenta);
     
   		$movil = $datosIdentificacion->campo('Movil',0);
   		$descripcion = $datosIdentificacion->campo('Descripcion',0);
   		$identificador =$datosIdentificacion->campo('Identificador',0);
   		$marca = $datosIdentificacion->campo('Marca',0);
   		$modelo = $datosIdentificacion->campo('Modelo',0);
   		$patente = $datosIdentificacion->campo('Patente',0);
		
		$fechai = $_REQUEST['diai'].'/'.$_REQUEST['mesi'].'/'.$_REQUEST['anoi']." ".$_REQUEST['horaInicio'].":00";
        $fechaf = $_REQUEST['diaf'].'/'.$_REQUEST['mesf'].'/'.$_REQUEST['anof']." ".$_REQUEST['horaFin'].":59";
        
        $fechaMysqlI = $_REQUEST['anoi'].'-'.$_REQUEST['mesi'].'-'.$_REQUEST['diai']." ".$_REQUEST['horaInicio'].':00';
        $fechaMysqlF = $_REQUEST['anof'].'-'.$_REQUEST['mesf'].'-'.$_REQUEST['diaf']." ".$_REQUEST['horaFin'].':59';
        
        
        //--------------------------------------        
        $datosPosicionamiento=BykomCliente::Consulta_Historico_Avl($cuenta,$fechaMysqlI,$fechaMysqlF,0,0,0);
        $registro = $datosPosicionamiento->cantidad();

        if ($registro > 1)
        {
        
        	$registro = $datosPosicionamiento->cantidad()-1;
        	$latitud = quitCero($datosPosicionamiento->campo('LATITUD',$registro));
        	$longitud = quitCero($datosPosicionamiento->campo('LONGITUD',$registro));
        
        	$velocidad = $datosPosicionamiento->campo('VELOCIDAD',$registro);
        	$sentido = $datosPosicionamiento->campo('SENTIDO',$registro);
        	$sentidoPalabra = BykomCliente::Obtener_Palabra_Sentido($sentido);
        	
        	
    //---------------------------------------------------//   	    
   	// Initialize
    MgInitializeWebTier($webconfigFilePath);
    $sessionId = $_REQUEST['SESSION'];
    $userInfo = new MgUserInformation($sessionId);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $featureService = $siteConnection->CreateService(MgServiceType::FeatureService);      
           
    //---------------------------------------------------//
    // Open the map
    $map = new MgMap();
    $map->Open($resourceService, AVL_MAP);

    //---------------------------------------------------//
    // Initialize some variables
    $layerName = "filtro".$filtroHistorico;
    
    $layerLegendLabel = $_REQUEST['horaInicio']." ".$_REQUEST['diai']."/".$_REQUEST['mesi']."/".$_REQUEST['anoi']." - ".$_REQUEST['horaFin']." ".$_REQUEST['diaf']."/".$_REQUEST['mesf']."/".$_REQUEST['anof'] . " (".$distanciaRecorrida . " Km)";
    $groupName = $identificador;
    $groupLegendLabel = $identificador;
    $colorRequest = $_REQUEST['colorId'];
    //---------------------------------------------------//
    // Does the temporary feature source already exist?
    // If not, create it
    $featureSourceName = "Session:$sessionId//filtro".$filtroHistorico.".FeatureSource"; 
    $resourceIdentifier = new MgResourceIdentifier($featureSourceName);
    
    $featureSourceExists = DoesResourceExist($resourceIdentifier, $resourceService);

    if (! $featureSourceExists) 
    {             
      // Create a temporary feature source to draw the lines on

      // Create a feature class definition for the new feature 
      // source
      $classDefinition = new MgClassDefinition();
      $classDefinition->SetName($layerName);
      $classDefinition->SetDescription("Lines to display.");
      $geometryPropertyName="SHPGEOM";
      $classDefinition->SetDefaultGeometryPropertyName( $geometryPropertyName); 
      
      // Create an identify property
      $identityProperty = new MgDataPropertyDefinition("KEY");
      $identityProperty->SetDataType(MgPropertyType::Int32);
      $identityProperty->SetAutoGeneration(true);
      $identityProperty->SetReadOnly(true); 
      // Add the identity property to the class definition
      $classDefinition->GetIdentityProperties()->Add($identityProperty);
      $classDefinition->GetProperties()->Add($identityProperty);
      
      // Create a name property
      $nameProperty = new MgDataPropertyDefinition("NAME");
      $nameProperty->SetDataType(MgPropertyType::String); 
      // Add the name property to the class definition
      $classDefinition->GetProperties()->Add($nameProperty);
      
      // Create a geometry property
      $geometryProperty = new MgGeometricPropertyDefinition($geometryPropertyName);   
      $geometryProperty->SetGeometryTypes(MgFeatureGeometricType::Surface);  
      // Add the geometry property to the class definition
      $classDefinition->GetProperties()->Add($geometryProperty); 
      
      // Create a feature schema
      $featureSchema = new MgFeatureSchema("SHP_Schema", "Line schema");
      // Add the feature schema to the class definition
      $featureSchema->GetClasses()->Add($classDefinition);             
      
      // Create the feature source
      //$wkt = $map->GetMapSRS();
      $wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
      $sdfParams = new MgCreateSdfParams("ArbitraryXY", $wkt, $featureSchema);  
      $featureService->CreateFeatureSource($resourceIdentifier, $sdfParams);          
    }  
    
    // Add the line to the feature source
    $batchPropertyCollection = new MgBatchPropertyCollection();
    
    $velocidadesExcedidas = new ArrayObject();
    $imagenesSentido = new ArrayObject();
    $contadorKmAuxiliar = 0;
    $contadorKm = 0;
    $j = 0;
    $k = 0;
    
  	/*if ($distanciaRecorrida < 11) {
   		$flechaSentidoCada = 0.5;	
   	} else if ($distanciaRecorrida < 101) {
   		$flechaSentidoCada = 5;	
   	} else if ($distanciaRecorrida < 2001) {
   		$flechaSentidoCada = 50;
   	} else {
   		$flechaSentidoCada = 100;
   	}*/
   	
   	$flechaSentidoCada = 0.5;
   	$diferenciaGrados = 45;
   	$velocidadRuta = 60;
   	$velocidadAnterior = 0;
   	$sentidoAnterior = 0;	
    for($i=0;  $i < $registro ; $i++ ) {
    	$x0 = quitCero($datosPosicionamiento->campo('LONGITUD',$i));
        $y0 = quitCero($datosPosicionamiento->campo('LATITUD',$i));
 		$x1 = quitCero($datosPosicionamiento->campo('LONGITUD',$i+1));
  		$y1 = quitCero($datosPosicionamiento->campo('LATITUD',$i+1));
    	$propertyCollection = MakeLine("Line".$i, $x0, $y0, $x1, $y1);
    	$batchPropertyCollection->Add($propertyCollection);
    	unset($propertyCollection);
    	$velocidadAux = $datosPosicionamiento->campo('VELOCIDAD',$i);
    	$huboExceso = false;
    	/*if (is_numeric($_SESSION['excesoVelocidad'])) {
    	   if ($velocidadAux > $_SESSION['excesoVelocidad']) {
    		$fechaAux = $datosPosicionamiento->campo('FECHA_MENSAJE',$i);
    		$puntoExcedido = new point();
    		$puntoExcedido->x = $x0;
    		$puntoExcedido->y = $y0;
    		$puntoExcedido->descripcion = "Fecha: ". $fechaAux ." - Velocidad:" . $velocidadAux; 
    		$velocidadesExcedidas[$j] = $puntoExcedido;
    		$j++;
    		$huboExceso = true;
    	   }
    	}*/
    	
    	
    	if ($mostrarSentido == 'true') {
    		if ($datosPosicionamiento->campo('EDAD_MENSAJE',$i) >= 255 ) continue;
    	    if ($datosPosicionamiento->campo('VELOCIDAD',$i) == '0' || $datosPosicionamiento->campo('VELOCIDAD',$i) == '00' || $datosPosicionamiento->campo('VELOCIDAD',$i) == '000') continue;
    		$distanciaEntrePuntos = sqrt(pow($y0 - $y1, 2) + pow($x0 - $x1, 2)) * 100;
    		
    		
    		/*$y = (abs($y0) - abs($y1) < 0) ? "+":"-";
    		$x = (abs($x0) - abs($x1) < 0) ? "+":"-";
    		$hipotenusa = sqrt(pow($x0 - $x1, 2) + pow($y0 - $y1, 2));
    		$altura = sqrt(pow($hipotenusa, 2) - pow($x0 - $x1, 2));
    		$gradosRadianes = asin($altura / $hipotenusa);
    		$sentidoActual = rad2deg($gradosRadianes);
    		if ($x == "+" && $y == "+") {
    			$sentidoActual = 180 + $sentidoActual; 
    		} else if ($x == "+" && $y == "-") {
    			$sentidoActual = 270 + $sentidoActual; 
    		} else if ($x == "-" && $y == "+") {
    			$sentidoActual = 90 + $sentidoActual; 	
    		} else if ($x == "-" && $y == "-") {
    			$sentidoActual = $sentidoActual; 
    		}*/
    		$sentidoActual = $datosPosicionamiento->campo('SENTIDO',$i);
    		$contadorKm = $contadorKm + $distanciaEntrePuntos;
    		$contadorKmAuxiliar = $contadorKmAuxiliar + $distanciaEntrePuntos;
    		$print = false;
    		if ($velocidadAux > $velocidadRuta) {
    			$flechaSentidoCada = 2.5;
    		} else {
    			$flechaSentidoCada = 0.5;
    		}
    		if ($velocidadAux > $velocidadRuta && $velocidadAnterior <= $velocidadRuta) $print = true;
    		if ($velocidadAux <= $velocidadRuta && $velocidadAnterior > $velocidadRuta) $print = true;
    		if ($contadorKmAuxiliar >= $flechaSentidoCada || $print) {
    			$puntoSentido = new point();
    			$puntoSentido->x = $x1;
    			$puntoSentido->y = $y1;
    			$puntoSentido->sentido = $sentidoActual;
    			$imagenesSentido[$k] = $puntoSentido;
    			$contadorKmAuxiliar = 0;
    			$k++;
    		}
    		$sentidoAnterior = $sentidoActual;
    		$velocidadAnterior = $velocidadAux;
    	}
    }
    
    // Add the batch property collection to the feature source
    $cmd = new MgInsertFeatures($layerName, $batchPropertyCollection); 
    $featureCommandCollection = new MgFeatureCommandCollection();
    $featureCommandCollection->Add($cmd);
    
    // Execute the "add" commands
    $featureService->UpdateFeatures($resourceIdentifier, $featureCommandCollection, false);     
    
    //---------------------------------------------------//
    $layerExists = DoesLayerExist($layerName, $map);
    if (! $layerExists )
    {
      // Create a new layer which uses that feature source         
        
      // Create a line rule to stylize the lines
      $ruleLegendLabel = 'Lines Rule';
      $filter = '';
      $color = ($colorRequest == '') ? 'FF'.COLOR_DEFAULT_RECORRIDO : "FF".substr($colorRequest,1);
      $factory = new LayerDefinitionFactory();
      $lineRule = $factory->CreateLineRule($ruleLegendLabel, $filter, $color, $thickness);
      
      
      // Create a line type style
      $lineTypeStyle = $factory->CreateLineTypeStyle($lineRule);
      
      // Create a scale range
      $minScale = '0';
      $maxScale = '1000000000000';
      $lineScaleRange = $factory->CreateScaleRange($minScale, $maxScale, $lineTypeStyle);   
    
      // Create the layer definiton
      $featureName = 'SHP_Schema:'.$layerName;
      $geometry = 'SHPGEOM';
      
      $layerDefinition = $factory->CreateLayerDefinition($featureSourceName, $featureName, $geometry, $lineScaleRange);
      
      //file_put_contents("c:\\hola.xml", $layerDefinition);
      
      //---------------------------------------------------//  
      // Add the layer to the map
      $newLayer = add_layer_definition_to_map($layerDefinition, $layerName, $layerLegendLabel, $sessionId, $resourceService, $map, false);
      // Add the layer to a layer group
      //echo '<script>alert("'.$identificador.'")</script>';
      add_layer_to_group($newLayer,"Historico ".$filtroHistorico." - ".$identificador , "Historico ".$filtroHistorico." - ".$identificador, $map);
    }
  
    // --------------------------------------------------//
    // Turn on the visibility of this layer.
    // (If the layer does not already exist in the map, it will be visible by default when it is added.
    // But if the user has already run this script, he or she may have set the layer to be invisible.)
    $layerCollection = $map->GetLayers();
    if ($layerCollection->Contains($layerName)) 
    {
      $linesLayer =$layerCollection->GetItem($layerName);
      $linesLayer->SetVisible(true);
    }
    
    $groupCollection = $map->GetLayerGroups();
    if ($groupCollection->Contains($groupName))
    {
      $analysisGroup =$groupCollection->GetItem($groupName);
      $analysisGroup->SetVisible(true);
    }    
    
    $pxIni = quitCero($datosPosicionamiento->campo('LONGITUD', 0));
    $pyIni = quitCero($datosPosicionamiento->campo('LATITUD', 0));
    $pxFin = quitCero($datosPosicionamiento->campo('LONGITUD', $registro));
    $pyFin = quitCero($datosPosicionamiento->campo('LATITUD', $registro));
    
    /***************** AGREGO EL INICIO Y EL FIN **************************/
    /*PUNTO INICIO*/
            $name1 = "Points".$cuenta.$filtroHistorico."a"; 
			$classDefinition = getPointClassDefinition($name1);
			$featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
			$featureSchema->GetClasses()->Add($classDefinition);             
			$featureSourceName = "Session:$sessionId//".$name1.".FeatureSource";
			$resourceIdentifier = new MgResourceIdentifier($featureSourceName);
			$wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
			$sdfParams = new MgCreateSdfParams("ArbitraryXY", $wkt, $featureSchema);
    		$featureService->CreateFeatureSource($resourceIdentifier, $sdfParams);
			$batchPropertyCollection = new MgBatchPropertyCollection();
			$wktReaderWriter = new MgWktReaderWriter();
			$agfReaderWriter = new MgAgfReaderWriter();
			$geometryFactory = new MgGeometryFactory();
			$propertyCollection = MakePointCar($movil, $descripcion, "Inicio", $marca, $modelo, $patente, $pxIni, $pyIni);
			$batchPropertyCollection->Add($propertyCollection);
			unset($propertyCollection);	
			$cmd = new MgInsertFeatures($name1, $batchPropertyCollection); 
			$featureCommandCollection = new MgFeatureCommandCollection();
			$featureCommandCollection->Add($cmd);
			$featureService->UpdateFeatures($resourceIdentifier, $featureCommandCollection, false);    
    		//*******************************************************************
    		// Create a new layer Icono del auto Inicio
    		$factory = new LayerDefinitionFactory();
			$resourceId = AVL_SYMBOLS;
    		$symbolName = 'MAPEO_INICIO';
    		$width = '16';  // unit = points
    		$height = '16'; // unit = points
    		$color = 'FF'.COLOR_DEFAULT_RECORRIDO_INI;
    		$markSymbol = $factory->CreateMarkSymbol($resourceId, $symbolName, $width, $height, $color);   
    		// Create a text symbol
    		$text = "IDENTIFICADOR";
    		$fontHeight="10";
    		$foregroundColor = COLOR_LEGEND_MOVIL;
    		$textSymbol = $factory->CreateTextSymbol($text, $fontHeight, $foregroundColor);

    		$legendLabel = 'trees';
    		$filter = '';
    		$pointRule = $factory->CreatePointRule($legendLabel, $filter, $textSymbol, $markSymbol);
      
    		$pointTypeStyle = $factory->CreatepointTypeStyle($pointRule);
      
    		$minScale = '0';
    		$maxScale = '1000000000000';
    		$pointScaleRange = $factory->CreateScaleRange($minScale, $maxScale, $pointTypeStyle);      

    		$featureName = 'PointSchema:'.$name1;
    		$geometry = 'GEOM';
    		$layerDefinition = $factory->CreateLayerDefinition($featureSourceName, $featureName, $geometry, $pointScaleRange);
    		$newLayer = add_layer_definition_to_map($layerDefinition, $name1, "Inicio", $sessionId, $resourceService, $map, false);
    		add_layer_to_group($newLayer, "Historico ".$filtroHistorico." - ".$identificador , "Historico ".$filtroHistorico." - ".$identificador, $map);

    		$layerCollection = $map->GetLayers();
    
    		if ($layerCollection->Contains($name1))
    		{
        		$pointsLayer = $layerCollection->GetItem($name1);
        		$pointsLayer->SetVisible(true);
    		}
    		
    	
    	
    	/*PUNTO FIN*/
    	// Create a feature class definition for the new feature source
            $name1 = "Points".$cuenta.$filtroHistorico."b"; 
			$classDefinition = getPointClassDefinition($name1);
			$featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
			$featureSchema->GetClasses()->Add($classDefinition);             
			$featureSourceName = "Session:$sessionId//".$name1.".FeatureSource";
			$resourceIdentifier = new MgResourceIdentifier($featureSourceName);
			$wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
			$sdfParams = new MgCreateSdfParams("ArbitraryXY", $wkt, $featureSchema);
    		$featureService->CreateFeatureSource($resourceIdentifier, $sdfParams);
			$batchPropertyCollection = new MgBatchPropertyCollection();
			$wktReaderWriter = new MgWktReaderWriter();
			$agfReaderWriter = new MgAgfReaderWriter();
			$geometryFactory = new MgGeometryFactory();
			$propertyCollection = MakePointCar($movil, $descripcion, "Fin", $marca, $modelo, $patente, $pxFin, $pyFin);
			$batchPropertyCollection->Add($propertyCollection);
			unset($propertyCollection);	
			$cmd = new MgInsertFeatures($name1, $batchPropertyCollection); 
			$featureCommandCollection = new MgFeatureCommandCollection();
			$featureCommandCollection->Add($cmd);
			$featureService->UpdateFeatures($resourceIdentifier, $featureCommandCollection, false);    
       		$factory = new LayerDefinitionFactory();

    		// Create a mark symbol
    		$resourceId = AVL_SYMBOLS;
    		$symbolName = 'MAPEO_FIN';
    		$width = '16';  // unit = points
    		$height = '16'; // unit = points
    		$color = 'FF'.COLOR_DEFAULT_RECORRIDO_FIN;
    		$markSymbol = $factory->CreateMarkSymbol($resourceId, $symbolName, $width, $height, $color);   
    
    		// Create a text symbol
    		$text = "IDENTIFICADOR";
    		$fontHeight="10";
    		$foregroundColor = COLOR_LEGEND_MOVIL;
    		$textSymbol = $factory->CreateTextSymbol($text, $fontHeight, $foregroundColor);

    		// Create a point rule.
    		$legendLabel = 'trees';
    		$filter = '';
    		$pointRule = $factory->CreatePointRule($legendLabel, $filter, $textSymbol, $markSymbol);
      
    		// Create a point type style.
    		$pointTypeStyle = $factory->CreatepointTypeStyle($pointRule);
      
    		// Create a scale range.
    		$minScale = '0';
    		$maxScale = '1000000000000';
    		$pointScaleRange = $factory->CreateScaleRange($minScale, $maxScale, $pointTypeStyle);      

    		// Create the layer definiton.
    		$featureName = 'PointSchema:'.$name1;
    		$geometry = 'GEOM';
    		$layerDefinition = $factory->CreateLayerDefinition($featureSourceName, $featureName, $geometry, $pointScaleRange);
    		
    		$newLayer = add_layer_definition_to_map($layerDefinition, $name1, "Fin", $sessionId, $resourceService, $map, false);
    		add_layer_to_group($newLayer, "Historico ".$filtroHistorico." - ".$identificador , "Historico ".$filtroHistorico." - ".$identificador, $map);

    		$layerCollection = $map->GetLayers();
    
    		if ($layerCollection->Contains($name1))
    		{
        		$pointsLayer = $layerCollection->GetItem($name1);
        		$pointsLayer->SetVisible(true);
    		}		
    		
    	//$topFor = (COUNT($velocidadesExcedidas) > COUNT($imagenesSentido)) ? COUNT($velocidadesExcedidas) : COUNT($imagenesSentido);
    	
    		for($r=0; $r < COUNT($imagenesSentido) ; $r=$r+1) {
    			//Agrego puntos de sentido cada X metros

    			$puntoSentido = $imagenesSentido[$r];
    			$name1 = "Points".$cuenta.$filtroHistorico."sent".$r; 
				$classDefinition = getPointClassDefinition($name1);
				
				$featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
				$featureSchema->GetClasses()->Add($classDefinition);             
	
				$featureSourceName = "Session:$sessionId//".$name1.".FeatureSource";
				$resourceIdentifier = new MgResourceIdentifier($featureSourceName);
				$wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
				$sdfParams = new MgCreateSdfParams("ArbitraryXY", $wkt, $featureSchema);
    			$featureService->CreateFeatureSource($resourceIdentifier, $sdfParams);
	
				$batchPropertyCollection = new MgBatchPropertyCollection();
				$wktReaderWriter = new MgWktReaderWriter();
				$agfReaderWriter = new MgAgfReaderWriter();
				$geometryFactory = new MgGeometryFactory();
   				//Add position actual
				$propertyCollection = MakeSimplePoint(BykomCliente::Obtener_Palabra_Sentido($puntoSentido->sentido), $puntoSentido->x, $puntoSentido->y);
				$batchPropertyCollection->Add($propertyCollection);
				unset($propertyCollection);	
				// Add the batch property collection to the feature source
				$cmd = new MgInsertFeatures($name1, $batchPropertyCollection); 
				$featureCommandCollection = new MgFeatureCommandCollection();
				$featureCommandCollection->Add($cmd);
				$featureService->UpdateFeatures($resourceIdentifier, $featureCommandCollection, false);    
	
    			/*********************************************/
    			// Create a new layer Icono Sentido
    			$factory = new LayerDefinitionFactory();
    			$resourceId = AVL_SYMBOLS;
    			$symbolName = obtener_Imagen_Flecha_Sentido($puntoSentido->sentido);
    			$width = '16';  // unit = points
    			$height = '16'; // unit = points
    			$color = 'FF'.COLOR_DEFAULT_RECORRIDO_FIN;
    			$markSymbol = $factory->CreateMarkSymbol($resourceId, $symbolName, $width, $height, $color);   

    			// Create a point rule.
    			$legendLabel = 'trees';
    			$filter = '';
    			$pointRule = $factory->CreatePointRule($legendLabel, $filter, $textSymbol, $markSymbol);
      
    			// Create a point type style.
    			$pointTypeStyle = $factory->CreatepointTypeStyle($pointRule);
    			$minScale = '0';
    			$maxScale = ZOOM_AVL_MAX_FLECHAS_SENTIDO;
    			$pointScaleRange = $factory->CreateScaleRange($minScale, $maxScale, $pointTypeStyle);      

    			$featureName = 'PointSchema:'.$name1;
    			$geometry = 'GEOM';
    			$layerDefinition = $factory->CreateLayerDefinition($featureSourceName, $featureName, $geometry, $pointScaleRange);
    			$newLayer = add_layer_definition_to_map($layerDefinition, $name1, BykomCliente::Obtener_Palabra_Sentido($puntoSentido->sentido), $sessionId, $resourceService, $map, false);
    			add_layer_to_group($newLayer, "Historico ".$filtroHistorico." - ".$identificador , "Historico ".$filtroHistorico." - ".$identificador, $map);

    			$layerCollection = $map->GetLayers();
    
    			if ($layerCollection->Contains($name1))
    			{
        			$pointsLayer = $layerCollection->GetItem($name1);
        			$pointsLayer->SetVisible(true);
    			}
    		}
    		unset($imagenesSentido);
    		unset($velocidadesExcedidas);
    /**********************************************************************/
    //  Save the map back to the session repository
    $sessionIdName = "Session:$sessionId//".AVL_MAP.".Map";
    $sessionResourceID = new MgResourceIdentifier($sessionIdName);
	$sessionResourceID->Validate();
    $map->Save($resourceService, $sessionResourceID);
    
    } // end registro >1
    else 
    {
    	//$_SESSION['hayEstadistica'] = 0;
    	echo "<script>alert('No se encontraron registros para el filtro aplicado');</script>"; 
    }
    //---------------------------------------------------//
}
catch (MgException $e)
{
	/*echo "<script language=\"javascript\" type=\"text/javascript\"> \n";
	echo "    alert(\" " . $e->GetMessage() . " \"); \n";
	echo "</script> \n";*/
}

///////////////////////////////////////////////////////////////////////////////////
?>

<script language="javascript" type="text/javascript">
        function OnPageLoad()
        {
        	parent.mapFrame.Refresh();
            <?php if ($registro > 0) { ?>
        		parent.mapFrame.ZoomToView(<?= $longitud ?>, <?= $latitud ?>, <?= ZOOM_AVL ?>, true);
        	<? } ?>	
        }
</script>

</body>
</html>


